package com.example.spring.utils;


import com.alibaba.fastjson.JSON;
import com.example.spring.dao.sys.*;
import com.example.spring.entity.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import redis.clients.jedis.JedisCluster;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户工具类
 *
 * @author ThinkGem
 * @version 2013-12-05
 */
public class UserUtils {

    private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
    private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
    private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
    private static OrganizationDao organizationDao = SpringContextHolder.getBean(OrganizationDao.class);
    private static PositionDao positionDa0 = SpringContextHolder.getBean(PositionDao.class);
    private static JedisCluster jedisCluster = SpringContextHolder.getBean(JedisCluster.class);


    public static final String USER_CACHE = "userCache";
    public static final String USER_CACHE_ID_ = "id_";
    public static final String USER_CACHE_NO_ = "no_";
    public static final String USER_CACHE_LOGIN_NAME_ = "ln";
    public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

    public static final String CACHE_ROLE_LIST = "roleList";
    public static final String CACHE_MENU_LIST = "menuList";
    public static final String CACHE_OFFICE_LIST = "officeList";
    public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";

    /**
     * 根据ID获取用户
     *
     * @param id
     * @return 取不到返回null
     */
    public static User get(String id) {
        //User user = JSON.parseObject(jedisCluster.hget(USER_CACHE, USER_CACHE_ID_ + id), User.class);
        User user = null;
        if (user == null) {
            user = userDao.get(id);
            if (user == null) {
                return null;
            }
            //测试
            jedisCluster.hset(USER_CACHE, USER_CACHE_ID_ + user.getId(), JSON.toJSONString(user));
            //CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
            //CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getNo(), user);
        }
        return user;
    }


//    /**
//     * 根据账号获取用户
//     *IDENTIFIER INTEGER
//     * @param userNo
//     * @return 取不到返回null
//     */
//    public static User getUserByNo(String userNo) {
//        User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + userNo);
//        if (user == null) {
//            user = userDao.getByNo(new User(null, userNo));
//            if (user == null) {
//                return null;
//            }
////			user.setRoleList(roleDao.findList(new Role(user)));
//            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
//            CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getNo(), user);
//        }
//        return user;
//    }

    /**
     * 清除当前用户缓存
     */
    public static void clearCache() {
//        removeCache(CACHE_ROLE_LIST);
//        removeCache(CACHE_MENU_LIST);
//        UserUtils.clearCache(getUser());
    }

    /**
     * 清除指定用户缓存
     *
     * @param user
     */
    public static void clearCache(User user) {
        //CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
        //CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getNo());
    }

    /**
     * 获取当前用户
     *
     * @return 取不到返回 new User()
     */
    public static User getUser() {
        User user = get("1");
        if (user != null) {
            return user;
        }
        return new User();
    }

    /**
     * 获取当前用户角色列表
     *
     * @return
     */
    // public static List<Role> getRoleList() {
    @SuppressWarnings("unchecked")
    //     List<Role> roleList = (List<Role>) getCache(CACHE_ROLE_LIST);
//		if (roleList == null){
//			User user = getUser();
//			if (user.isAdmin()){
//				roleList = roleDao.findAllList(new Role());
//			}else{
//				Role role = new Role();
//				role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
//				roleList = roleDao.findList(role);
//			}
//			putCache(CACHE_ROLE_LIST, roleList);
//		}
//        return roleList;
//    }

    /**
     * 获取当前用户授权菜单
     *
     * @return
     */
    public static List<Menu> getMenuList() {
        //@SuppressWarnings("unchecked")
        //List<Menu> menuList = (List<Menu>) getCache(CACHE_MENU_LIST);
        List<Menu> menuList = new ArrayList<>();
        User user = getUser();
        if (user.isAdmin()) {
            menuList = menuDao.findAllList(new Menu());
        } else {
            Menu m = new Menu();
            m.setUserId(user.getId());
            menuList = menuDao.findByUserId(m);
        }
        return menuList;
    }

//    /**
//     * 判断当前用户是否为管理员权限
//     *
//     * @return
//     */
//    public static boolean isAdmin() {
//        User user = getUser();
//        if (user.getId().equals("1")) {
//            return true;
//        } else {
//            return false;
//        }
//    }
//
//    /**
//     * 判断用户是否为超级管理员
//     *
//     * @return
//     */
//    public static boolean isSuperAdmin() {
//        User user = getUser();
//        if (user.getId().equals("1")) {
//            return true;
//        } else {
//            return false;
//        }
//    }

//    /**
//     * 获取当前用户的管理渠道
//     *
//     * @return
//     */
//    public static String manageCompany() {
//        User user = getUser();
//        List<String> mcList = user.getManageChannelList(); //获取当前渠道信息
//        String orgType = user.getCompany().getType(); //获取当前用户的所属公司
//        String mcStr = "";
//        if (orgType.equals("1")) {
//            //融数
//            if (mcList != null && mcList.size() > 0) {
//                mcStr = mcList.get(0);
//            }
//        } else {
//            //非融数
//            mcStr = user.getCompany().getCode();
//        }
//        return mcStr;
//    }

    /**
     * 获取所属公司最大的员工编号
     */
    public static String getUserMaxNoStr(Organization organization) {
        UserOthProObj userOthProObj = new UserOthProObj();
        userOthProObj.setCompanyID(organization.getId());
        userOthProObj.setUserNOStr(organization.getSimpleCode());

        userOthProObj = userDao.getUserMaxNo(userOthProObj);
        int uno = userOthProObj.getMaxNo() + 1; //最大用户编号加1
        String userNOStr = String.valueOf(uno);
        //进行补充0操作
        userNOStr = StringUtils.leftPad(userNOStr, 4, "0");
        userNOStr = organization.getSimpleCode() + userNOStr;
        return userNOStr;
    }

//    /**
//     * @param sourcelist
//     * @param parentId
//     * @return
//     */
//    public static String sortList(List<Menu> sourcelist, String parentId) {
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0; i < sourcelist.size(); i++) {
//            Menu e = sourcelist.get(i);
//            if (!getUser().isAdmin() && !"common".equals(Global.getConfig("projectCode")) && (!e.getSystemSign().equals(Global.getConfig("projectCode")) && !e.getSystemSign().equals(Global.getConfig("common")))) {
//                continue;
//            }
//            if (e.getParent() != null && e.getParent().getId() != null
//                    && e.getParent().getId().equals(parentId)) {
//                e.hasChild(StringUtils.isBlank(e.getHref()));
//                sb.append("<li class=\"" + (e.hasChild() ? "treeview" : "") + "\">").append("\n");
//                sb.append("    <a href=\"#\" ").append(e.hasChild() ? "" : "data-action=\"" + SpringContextHolder.getApplicationContext().getApplicationName() + e.getHref() + "\" ").append("\">").append("\n");
//                sb.append("        <i class=\"" + (e.hasChild() ? e.getIcon() : "fa fa-circle-o") + "\"></i> <span>" + e.getName() + "</span> " + (e.hasChild() ? "<i class=\"fa fa-angle-left pull-right\"></i>" : "")).append("\n");
//                sb.append("    </a>").append("\n");
//                boolean flag = false;
//                // 判断是否还有子节点, 有则继续获取子节点
//                for (int j = 0; j < sourcelist.size(); j++) {
//                    Menu child = sourcelist.get(j);
//                    if (child.getParent() != null && child.getParent().getId() != null
//                            && child.getParent().getId().equals(e.getId())) {
//                        if (!flag) {
//                            sb.append("<ul class=\"treeview-menu\">").append("\n");
//                            flag = true;
//                        }
//                        sb.append(sortList(sourcelist, e.getId()));
//                        break;
//                    }
//                }
//                if (flag) {
//                    sb.append("</ul>").append("\n");
//                }
//                sb.append("</li>").append("\n");
//            }
//        }
//        return sb.toString();
//    }


//    /**
//     * 获取当前用户授权菜单
//     *
//     * @return
//     */
//    public static String getMenuListString() {
//        @SuppressWarnings("unchecked")
//        List<Menu> menuList = getMenuList();
//        return sortList(menuList, "1");
//    }

    /**
     * 获取当前用户授权菜单的树形结构数据
     * 递归获取菜单对象
     */
    public static MenuNode getMenuTreeString(String id, List<Menu> menuList) {
        //在当前用户菜单权限范围内查询
        MenuNode menuNode = getMenuObj(id, menuList);
        List<MenuNode> childMenuNodes = getMenuList(id, menuList);
        //遍历子节点
        if (childMenuNodes != null && childMenuNodes.size() > 0) {
            for (MenuNode mn : childMenuNodes) {
                if (StringUtils.isNotBlank(mn.getMenuId())) {
                    MenuNode m = getMenuTreeString(mn.getMenuId(), menuList); //递归
                    if (m.getChildren() == null || m.getChildren().size() == 0) {
                        m.setChildren(null);
                    }
                    menuNode.getChildren().add(m);
                }
            }
        }
        return menuNode;
    }

    /**
     * 根据节点ID,从list集合中
     *
     * @param id
     * @param menuList
     * @return
     */
    public static MenuNode getMenuObj(String id, List<Menu> menuList) {
        MenuNode menuNode = new MenuNode();
        for (Menu m : menuList) {
            if (id.equals(m.getId())) {
                menuNode.setTo(m.getTo());
                menuNode.setImage(m.getIcon());
                menuNode.setMenuId(m.getId());
                menuNode.setKey(m.getId());
                menuNode.setName(m.getName());
                menuNode.setParentId(m.getParentId());
                menuNode.setIsShow(m.getIsShow());
                menuNode.setRemarks(m.getRemarks());
                menuNode.setSystemSign(m.getSystemSign());

                break;
            }
        }
        return menuNode;
    }

    /**
     * 根据父节点ID，查询集合中的节点信息
     */
    public static List<MenuNode> getMenuList(String pid, List<Menu> menuList) {
        List<MenuNode> mls = Lists.newArrayList();
        for (Menu m : menuList) {
            if (pid.equals(m.getParentId())) {
                MenuNode menuNode = new MenuNode();
                menuNode.setTo(m.getTo());
                menuNode.setImage(m.getIcon());
                menuNode.setMenuId(m.getId());
                menuNode.setKey(m.getId());
                menuNode.setName(m.getName());
                menuNode.setParentId(m.getParentId());
                menuNode.setIsShow(m.getIsShow());
                menuNode.setRemarks(m.getRemarks());
                menuNode.setSystemSign(m.getSystemSign());
                mls.add(menuNode);
            }
        }
        return mls;
    }


    /**
     * 获取当前用户授权菜单的树形结构数据
     * 递归获取菜单对象
     */
    public static OrganizationNode getOrgTreeString(String id, List<Organization> orgList) {
        //在当前用户菜单权限范围内查询
        OrganizationNode orgNode = getOrgObj(id, orgList);
        List<OrganizationNode> childOrgNodes = getOrgList(id, orgList);
        List<OrganizationNode> orgListNodes = Lists.newArrayList();
        //遍历子节点
        if (childOrgNodes != null && childOrgNodes.size() > 0) {
            for (int i = 0; i < childOrgNodes.size(); i++) {
                OrganizationNode on = childOrgNodes.get(i);
                if (StringUtils.isNotBlank(on.getOrgId())) {
                    OrganizationNode o = getOrgTreeString(on.getOrgId(), orgList); //递归
                    orgListNodes.add(o);
                }
            }
        }
        if (orgListNodes.size() > 0) {
            orgNode.setChildren(orgListNodes);
        }
        return orgNode;
    }

    /**
     * 根据节点ID,从list集合中
     *
     * @param id
     * @param orgList
     * @return
     */
    public static OrganizationNode getOrgObj(String id, List<Organization> orgList) {
        OrganizationNode orgNode = new OrganizationNode();
        for (Organization o : orgList) {
            if (id.equals(o.getId())) {
                orgNode.setParentId(o.getParentId());
                orgNode.setMaster(o.getMaster());
                orgNode.setOrgCode(o.getCode());
                orgNode.setOrgId(o.getId());
                orgNode.setOrgName(o.getName());
                orgNode.setOrgType(o.getType());
                orgNode.setKey(o.getId());
                orgNode.setParentIds(o.getParentIds());
                orgNode.setGrade(o.getGrade());
                orgNode.setSimpleCode(o.getSimpleCode());
                break;
            }
        }
        return orgNode;
    }

    /**
     * 根据父节点ID，查询集合中的节点信息
     */
    public static List<OrganizationNode> getOrgList(String pid, List<Organization> orgList) {
        List<OrganizationNode> mls = Lists.newArrayList();
        for (Organization o : orgList) {
            if (pid.equals(o.getParentId())) {
                OrganizationNode orgNode = new OrganizationNode();
                orgNode.setParentId(o.getParentId());
                orgNode.setMaster(o.getMaster());
                orgNode.setOrgCode(o.getCode());
                orgNode.setOrgId(o.getId());
                orgNode.setOrgName(o.getName());
                orgNode.setOrgType(o.getType());
                orgNode.setKey(o.getId());
                orgNode.setParentIds(o.getParentIds());
                orgNode.setGrade(o.getGrade());
                orgNode.setSimpleCode(o.getSimpleCode());
                mls.add(orgNode);
            }
        }
        return mls;
    }

//    /**
//     * 获取授权主要对象
//     */
//    public static Subject getSubject() {
//        return SecurityUtils.getSubject();
//    }

//    /**
//     * 获取当前登录者对象
//     */
//    public static Principal getPrincipal() {
//        try {
//            Subject subject = SecurityUtils.getSubject();
//            Principal principal = (Principal) subject.getPrincipal();
//            if (principal != null) {
//                return principal;
//            }
////			subject.logout();
//        } catch (UnavailableSecurityManagerException e) {
//
//        } catch (InvalidSessionException e) {
//
//        }
//        return null;
//    }

//    /**
//     * 获取用户当前管理渠道
//     *
//     * @return
//     */
//    public static String getCurrentChannel() {
//        Principal principal = getPrincipal();
//        if (principal != null) {
//            return principal.getCurrentChannel();
//        }
//        return null;
//    }

//    /**
//     * 获取当前用户有权限访问的部门
//     *
//     * @return
//     */
//    public static List<Organization> getOfficeList() {
//        @SuppressWarnings("unchecked")
//        List<Organization> officeList = (List<Organization>) getCache(CACHE_OFFICE_LIST);
//        if (officeList == null) {
//            User user = getUser();
//            if (user.isAdmin()) {
//                officeList = organizationDao.findAllList(new Organization());
//            } else {
//                Organization office = new Organization();
//                office.getSqlMap().put("dsf", BaseService.dataScopeFilter(user, "a", ""));
//                officeList = organizationDao.findList(office);
//            }
//            putCache(CACHE_OFFICE_LIST, officeList);
//        }
//        return officeList;
//    }

    /**
     * 获取当前用户有权限访问的部门
     *
     * @return
     */
    public static List<Organization> getOfficeAllList() {
//        @SuppressWarnings("unchecked")
//        List<Organization> officeList = (List<Organization>) getCache(CACHE_OFFICE_ALL_LIST);
//        if (officeList == null) {
//            officeList = organizationDao.findAllList(new Organization());
//        }
//        return officeList;
        return organizationDao.findAllList(new Organization());
    }

    /**
     * 根据机构编号获取机构ID
     *
     * @return
     */
    public static Organization getOrgByNo(String orgCode) {
        Organization organization = new Organization();
        organization.setCode(orgCode);
        organization = organizationDao.getOrgByNo(organization);
        return organization;
    }

    /**
     * 根据机构ID,查询对应的岗位信息
     */
    public static List<Position> selectPositionByOrgId(String orgId) {
        PositionOrg po = new PositionOrg();
        po.setOrgId(orgId);
        return positionDa0.selectPositionByOrgId(po);
    }

//    public static Session getSession() {
//        try {
//            Subject subject = SecurityUtils.getSubject();
//            Session session = subject.getSession(false);
//            if (session == null) {
//                session = subject.getSession();
//            }
//            if (session != null) {
//                return session;
//            }
////			subject.logout();
//        } catch (InvalidSessionException e) {
//
//        }
//        return null;
//    }

    // ============== User Cache ==============

//    public static Object getCache(String key) {
//        return getCache(key, null);
//    }

//    public static Object getCache(String key, Object defaultValue) {
////		Object obj = getCacheMap().get(key);
//        Object obj = getSession().getAttribute(key);
//        return obj == null ? defaultValue : obj;
//    }

    public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
        //getSession().setAttribute(key, value);
    }

    public static void removeCache(String key) {
//		getCacheMap().remove(key);
        //getSession().removeAttribute(key);
    }

//	public static Map<String, Object> getCacheMap(){
//		Principal principal = getPrincipal();
//		if(principal!=null){
//			return principal.getCacheMap();
//		}
//		return new HashMap<String, Object>();
//	}

//    /**
//     * 根据登录名、邮箱、手机查询用户
//     *
//     * @param userNo
//     * @return 取不到返回null
////     */
//    public static User getByNoOrMobileOrEmail(String userNo) {
//        User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + userNo);
//        if (user == null) {
//            user = userDao.getByNoOrMobileOrEmail(new User(null, userNo));
//            if (user == null) {
//                return null;
//            }
//            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
//            CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getNo(), user);
//        }
//        return user;
//    }


    /**
     * 通过no进行查询，返回所有的用户编号和名称map集合
     *
     * @param no
     * @return
     */
    public static List<User> findUserList(List<String> no) {
        if (no == null || no.size() == 0) {
            return null;
        }
        List<User> userList = userDao.findUserInfoList(no);
        return userList;
    }

    /**
     * 根据用户编号查询用户信息
     *
     * @param no
     * @return
     */
    public static User findUserInfo(String no) {
        if (no == null || "".equals(no)) {
            return null;
        }
        User user = userDao.findUserInfo(no);
        return user;
    }

    /**
     * 通过no进行查询，返回所有的用户编号和名称map集合
     *
     * @param no
     * @return
     */
    public static List<Map<String, String>> findUserData(List<String> no) {
        if (no == null || no.size() == 0) {
            return null;
        }
        List<User> userList = userDao.findUserInfoList(no);
        List<Map<String, String>> mapList = Lists.newArrayList();
        Map<String, String> map = null;
        if (userList != null && userList.size() > 0) {
            for (User u : userList) {
                map = Maps.newHashMap();
                map.put(u.getNo(), u.getName());
                mapList.add(map);
            }
            return mapList;
        }
        return null;
    }

    /**
     * 定制根据查询查询用户分页列表
     *
     * @param page
     * @param user
     * @return
     */
    public Page<User> findUserList(Page<User> page, User user) {
        // 设置分页参数
        user.setPage(page);
        // 执行分页查询
        page.setList(userDao.findList(user));
        return page;
    }

    /**
     * 定制查询岗位列表
     *
     * @param map
     * @return
     */
    public Page<HashMap> getPositionOrgList(Map map) {
        // 设置分页参数
        Page page = (Page) map.get("page");
        // 执行分页查询
        page.setList(positionDa0.findPositionOrgList(map));
        return page;
    }

//    /**
//     * 根据当前用户的渠道信息,查询对应的渠道信息集合
//     *
//     * @return
//     */
//    public static List<Organization> manageCompanyList() {
//        User user = getUser();
//        List<Organization> list = Lists.newArrayList();
//        if (StringUtils.isNotBlank(user.getManageChannel())) {
//            String manageChannel = StringUtils.subSplitToInStr(user.getManageChannel());
//            User userObj = new User();
//            userObj.setManageChannel(manageChannel);
//            list = organizationDao.findmanageChannelList(userObj);
//        }
//        return list;
//    }
}